<template>
	<view class="scrool-page">
		<view class="list-cont">
			<scroll-view  class="scrool-more" style="height: 100%" scroll-y="true" scroll-with-animation="true">
				<view v-for="(item,index) in productList" :key="item.boxCode">
					<uni-card :title="'序号:'+(index+1)">
						<text class="uni-body">箱码：{{ item.boxCode }}</text><br>
					</uni-card>
				</view>
			</scroll-view>
		</view>
		
		<view class="footer">
			<button type="default" size='mini' @click="reduceData" style="width:48%; margin-left:1%;" v-if="!userflag">减码</button>
			<button type="default" size='mini' @click="reduceData" style="width:48%; margin-left:1%;" v-else>加箱</button>
			<button type="default" size='mini' @click="submit" style="width:49%; margin-left:1%;">完成</button>
		</view>
		
		<uni-popup ref="alertDialog" type="dialog" :is-mask-click="false">
			<uni-popup-dialog type="success" cancelText="关闭" confirmText="确定" title="提示" :before-close="true" :content="content" @confirm="dialogConfirm"
				@close="dialogClose" >
			</uni-popup-dialog>
		</uni-popup>
		
		<uni-popup ref="reduceDialog" type="dialog" :is-mask-click="false">
			<uni-popup-dialog type="success" cancelText="关闭" confirmText="确定" title="提示" :before-close="true" :content="reduceContent" @confirm="reduceConfirm"
				@close="reduceClose">
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import Vue from 'vue';
	import { getToken } from '@/utils/auth';
	import common from '../../pages/common/common.js'
	var globalEvent = uni.requireNativePlugin('globalEvent');
	var main, receiver, filter;
	var ScanDeviceClass = plus.android.importClass("android.device.ScanDevice");
	var scanDevice;
	export default {
		data() {
			return {
				productList:[],
				userflag:false,
				code:'',
				content:'',
				codeEqualQty:'',
				boxCode:'',
				count:0,
				content:'',
				reduceContent:'',
				reduceCode:'',
				reduceNumkber:'',
				reducePatch:'',
				reduceCount:0,
				baseUrl:getApp().globalData.config.baseUrl,
				userName:this.$store.state.user.name,
				orgId:getApp().globalData.config.orgId,
			}
		},
		
		onShow() {
			this.orgId = uni.getStorageSync('orgId');
			scanDevice = new ScanDeviceClass();
			scanDevice.openScan(); // 打开扫描
			scanDevice.setOutScanMode(0); // 扫描模式				
			this.initScan();
			this.registerScan();
		},
		
		onHide: function() {
			this.unregisterScan();
		},
		
		destroyed: function() {
			this.unregisterScan();
		},
		
		onBackPress(options) {
			var that = this;
			if (options.from === 'navigateBack') {
			     return false;
			}
			//that.unregisterScan();
			uni.navigateBack({  //uni.navigateTo跳转的返回，默认1为返回上一级
			    delta: 1
			});
			return true;
		},
		
		onLoad: function (option){
			// var tempList = {code:option.code,codeEqualQty:option.codeEqualQty,boxCode:option.boxCode,flag:false};
			// this.productList.push(tempList);
			// 添加打印状态监听
			this.orgId = uni.getStorageSync('orgId');
			globalEvent.addEventListener('onPrintCallback', function(e) {
				uni.showToast({
					title: 'state: ' + JSON.stringify(e),
					duration: 2000
				});
				if (e.key == 0) {
					uni.showToast({
						title: '打印成功',
						duration: 2000
					});
				} else if (e.key == 3) {
					uni.showToast({
						title: '缺纸',
						duration: 2000
					});
				}
			});
			//打印机版本获取回调
			globalEvent.addEventListener('onVersion', function(e) {
				// uni.showToast({
				// 	title: 'version: ' + JSON.stringify(e),
				// 	duration: 2000
				// });
			});
			
			globalEvent.addEventListener('getsupportprint', function(e) {
				console.log('key: ' + JSON.stringify(e));
				// uni.showToast({
				// 	title: 'key: ' + JSON.stringify(e),
				// 	duration: 2000
				// });
			});
		},
		
		methods: {
			initScan() {
				let _this = this;
				main = plus.android.runtimeMainActivity(); //获取activity  
				var IntentFilter = plus.android.importClass('android.content.IntentFilter');
				filter = new IntentFilter();
				filter.addAction("scan.rcv.message"); // 换你的广播动作  
				receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
					onReceive: function(context, intent) {
						plus.android.importClass(intent);
						let code = intent.getByteArrayExtra('barocode');
					    let codeStr = common.utf8ByteToUnicodeStr(code);
						scanDevice.stopScan();// 停止扫描
						_this.buttonScan(codeStr);
						_this.viewScan(codeStr);												
					}
				});				
			},
			
			registerScan() {
				main.registerReceiver(receiver, filter);
			},
			
			unregisterScan() {
				main.unregisterReceiver(receiver);
			},
			
			buttonScan(codeStr){
				if(this.userflag){
					return;
				}
				if(codeStr == null || codeStr == ''){
					uni.showToast({
						title: '请扫描数据',
						icon: 'error',
						duration: 2000
					});
					return;
				}
				var result = common.scanCode(codeStr);
				if(result[0] != "C"){
					uni.showToast({
						title: '请扫描箱号',
						icon: 'error',
						duration: 5000
					});
					return;
				}
				var flag = false;
				for(var j=0;j<this.productList.length;j++){
					if(this.productList[j].boxCode == result[1]){
						flag = true;
						break;
					}		
				}
				if(flag){
					uni.showToast({
						title: '此数据已存在',
						icon: 'error',
						duration: 2000
					});
					return;
				}else{
					this.boxCode = result[1];
					this.judgeAeaCode(result[1]);
				}									
			},
			
			reduceData(){
				if(this.userflag){
					this.userflag = false;
				}else{
					this.userflag = true;
				}
			},
			
			viewScan(codeStr){
				if(!this.userflag){
					return;
				}
				var result = common.scanCode(codeStr);
				if(result[0] == "C"){
					this.reducePatch = result[1];
					this.reduceContent = '箱码：'+this.reducePatch+'\n';
				}else{
					uni.showToast({
						title: '请扫描箱码',
						icon: 'error',
						duration: 5000
					});
					this.userflag = false;
				}
				this.$refs.reduceDialog.open();
			},
			
			dialogConfirm(){
				//如果三个码都扫描完成
				var that = this;
				if(that.code == null || that.code == ''){
					uni.showToast({
						title: '请扫描物料编码',
						icon: 'none',
						duration: 3000
					});
					return;
				}else if(that.codeEqualQty == null || that.codeEqualQty == ''){
					uni.showToast({
						title: '请扫描数量',
						icon: 'none',
						duration: 3000
					});
					return;
				}else if(that.boxCode == null || that.boxCode == ''){
					uni.showToast({
						title: '请扫描箱码',
						icon: 'none',
						duration: 3000
					});
					return;
				}else{
					that.judgeAeaCode(that.boxCode);
				}
			},
			
			judgeAeaCode(codeStr){
				//显示加载框
				uni.showLoading({
					title: "加载中",
					mask:true
				});	
				var that = this;
				//根据箱号查询条码主档
				uni.request({
					url:that.baseUrl+'/system/barcode/box',
					data:{
						userName:that.userName,
						boxCode:codeStr	,
						orgId:that.orgId,
					},
					method: 'POST',
					header:{
						'authorization':  getToken()
					},
					dataType:'json',
					success: (res) =>{
						//隐藏加载框
						uni.hideLoading();
						if(res.data.code == '200' || res.data.code == 200) {	
							var result = res.data.data;
							if(result.storageArea != 'R'){
								uni.showToast({
									title: '此箱不在待入库区',
									icon: 'none',
									duration: 5000
								});
							}else{
								that.queryState(codeStr);
								//var tempList = {code:that.code,codeEqualQty:that.codeEqualQty,boxCode:that.boxCode,flag:false};
								//var tempList = {boxCode:that.boxCode,flag:false};
								//that.productList.push(tempList);	
								//that.$refs.alertDialog.close();
							}
							that.code = '';
							that.codeEqualQty='';
							that.boxCode ='';
							that.count = '0';							
						}else{
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 2000
							});
							return;
						}
						
					},							
				})
			},
			
			queryState(codeStr){
				var that = this;
				uni.request({
					url:that.baseUrl+'/system/overstorage/isOverStorage',
					data:{
						userCode:that.userName,
						boxnum:codeStr,
						orgId:that.orgId,
					},
					method: 'POST',
					header:{
						'authorization':  getToken()
					},
					dataType:'json',
					success: (res) =>{
						//隐藏加载框
						uni.hideLoading();
						console.log(res);
						if(res.data.code == '200' || res.data.code == 200) {	
							that.boxCode = codeStr;
							var tempList = {boxCode:that.boxCode,flag:false};
							that.productList.push(tempList);							
						}else{
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 2000
							});
							return;
						}
						
					},							
				})
			},
			
			dialogClose(){
				this.code = '';
				this.codeEqualQty='';
				this.boxCode ='';
				this.count = '0';
				this.$refs.alertDialog.close();
			},
			
			reduceConfirm(){
				var tempList = [];
				for(var i=0;i<this.productList.length;i++){
					if(this.productList[i].boxCode == this.reducePatch){
						
					}else{
						tempList.push(this.productList[i]);
					}
				}
				this.productList = [];
				this.productList = tempList;
				this.$refs.reduceDialog.close();
				this.reduceCode = '';
				this.reduceNumkber='';
				this.reducePatch ='';
				this.reduceCount = 0;
				this.userflag = false;				
			},
			
			reduceClose(){
				this.reduceCode = '';
				this.reduceNumkber='';
				this.reducePatch ='';
				this.reduceCount = 0;
				this.userflag = false;
				this.$refs.reduceDialog.close();
			},
			
			//生成越库单
			submit(){
				var that = this;
				//显示加载框
				uni.showLoading({
					title: "加载中",
					mask:true
				});	
				uni.request({
					url:that.baseUrl+'/system/overstorage/add1',
					data:{
						productList : that.productList,
						userName:that.userName,
						orgId:that.orgId,
					},
					method: 'POST',
					header:{
						'authorization':  getToken()
					},
					dataType:'json',
					success: (res) =>{
						//隐藏加载框
						uni.hideLoading();
						if(res.data.code == '200') {	
							uni.showToast({
								title: '操作成功',
								icon: 'success',
								duration: 2000
							});
							//that.unregisterScan();
							uni.navigateBack({  //uni.navigateTo跳转的返回，默认1为返回上一级
							    delta: 1
							});
						}else{
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 3000
							});
							return;
						}
						
					},							
				})
			},
		}
	}
</script>

<style lang="scss">
	.main {
		background-color: #fff;
		height: 300upx;
		align-items: center;
		margin-top: 10upx;
	}
	.text-content {
		font-size: 48rpx;
		text-align: center;
	}
	
	.city {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
		justify-content: flex-start;
		// width: 160rpx;
		margin-left: 4px;
		font-size: 26rpx;
	}
	
	.input-view {
		display: flex;
		flex-direction: row;
		flex: 1;
		//background-color: #f8f8f8;
		height: 30px;
		padding: 0 80px;
		flex-wrap: nowrap;
		margin: 7px 0;
		line-height:30px;
		font-size: 26rpx;
	}
	page {
		width: 100%;
		height: 100%;
	}
	
	
	.scrool-page {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100%;
	}
	
	.header-cont {
		width: 100%;
		height: 110rpx;
		line-height: 100rpx;
		text-align: center;
		// background: red;
	}
	
	.list-cont {
		flex: 1;
		position: relative;
	
		.scrool-more {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
		}
	
		.list {
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background: #e0e0e0;
	
		}
	}
	
	
	.footer {
		color: #fff;
		line-height: 100rpx;
		flex: 0 0 100rpx;
		/* 不放大不缩小固定100rpx */
	}
</style>
